package com.key.puzzlemodel.puzzlephoto

import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.key.puzzlemodel.R
import com.key.puzzlemodel.databinding.FragmentPuzzPhotoBinding
import com.key.puzzlemodel.mvvm.BaseMVVMFragment
import com.key.puzzlemodel.mvvm.BaseMVVMViewModel
import com.key.puzzlemodel.util.RecycItemTouchHelperCallback
import java.util.*

/**
 * @功能描述: 拼图相册 fragment
 * @创建时间: 2021/12/30
 * @创建者: 阳
 * @修改时间: 2021/12/30
 * @修改者: 阳
 */
class PuzzlePhotoFragment : BaseMVVMFragment<FragmentPuzzPhotoBinding, BaseMVVMViewModel>(),
    View.OnClickListener {

    override val layoutId: Int
        get() = R.layout.fragment_puzz_photo

    private lateinit var photoItemFragment: PuzzlePhotoItemFragment

    private lateinit var onSelectPhotoListener: ((ArrayList<String>) -> Unit)// 选中照片回调
    private lateinit var onTakePhotoListener: (() -> Unit)// 点击拍照回调

    //照相选择的数量
    var photoSize = -1
    var limitMin = -1 //图片选取最小参数
    var limitMax = -1 //图片选取最大参数

    lateinit var photoAdapter: MediaCheckedAdapter

    // 1、至少选中一张图片时，底部弹出已选择的图片板块；
    // 2、左上角动态显示已选择的张数；
    // 3、长按已选择的图片拖动可移动图片顺序；
    // 4、点击已选择的图片右上角“×”删除该图片；
    // 5、左划显示更多已选中的图片；
    // 6、点击“下一步”进入右侧编辑页；
    // 7、若删除全部已选择的图片，则收起底部板块；
    // 8、上限最多可添加20张图片，超过20张toast提示：最多可添加20张
    override fun initView(savedInstanceState: Bundle?) {
        mVDB.clickListener = this

        photoAdapter = MediaCheckedAdapter(ArrayList());
        mVDB.rvCheckedMedia.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        mVDB.rvCheckedMedia.adapter = photoAdapter

        val helper = ItemTouchHelper(RecycItemTouchHelperCallback(photoAdapter!!))
        helper.attachToRecyclerView(mVDB.rvCheckedMedia)


        val fragment = childFragmentManager.findFragmentByTag("photo_select_item_fragment")
        if (null != fragment && fragment is PuzzlePhotoItemFragment) {
            photoItemFragment = fragment

            photoItemFragment.setOnPhotoSelectedListener {

                //选取固定的数量
                if (photoSize != -1) {

                    if (photoSize == 1) {
                        photoAdapter.addSelectPhoto(it.toString())
                        onSelectPhotoListener.invoke(photoAdapter.mData)
                    } else {
                        if (photoAdapter.itemCount >= photoSize) {
                            Toast.makeText(requireActivity(), "最多可添加20张", Toast.LENGTH_SHORT).show()
                            return@setOnPhotoSelectedListener
                        }

                        //Log.e("返回数据", "-- $it")
                        photoAdapter.addSelectPhoto(it.toString())
                        mVDB.rvCheckedMedia.scrollToPosition(photoAdapter.itemCount - 1)

                        mVDB.rlAlbumBottomBar.visibility = View.VISIBLE
                        setPhotoNumberText(photoAdapter.itemCount)
                    }
                } else if (limitMax != -1 && limitMin != -1) {
                    //选取范围数量
                    if (photoAdapter.itemCount >= limitMax) {
                        Toast.makeText(requireActivity(), "单次选择媒体不能超过${limitMax}个", Toast.LENGTH_SHORT).show()
                        return@setOnPhotoSelectedListener
                    }

                    //Log.e("返回数据", "-- $it")
                    photoAdapter.addSelectPhoto(it.toString())
                    mVDB.rvCheckedMedia.scrollToPosition(photoAdapter.itemCount - 1)

                    mVDB.rlAlbumBottomBar.visibility = View.VISIBLE
                    setPhotoNumberText(photoAdapter.itemCount)
                }
            }
        }
        photoAdapter.setOnItemClickListener(object : MediaCheckedAdapter.OnItemClickListener {
            override fun onDelete(position: Int) {
                //如果没有选中照片，列表数据为0，则隐藏选中列表
                if (photoAdapter.itemCount == 0) {
                    mVDB.rlAlbumBottomBar.visibility = View.GONE
                }
                setPhotoNumberText(photoAdapter.itemCount)
            }

            override fun onItemClick(position: Int) {

            }

            override fun onMove() {

            }
        })
    }

    fun loadPhoto() {
        if (this::photoItemFragment.isInitialized) {
            photoItemFragment.loadPhoto(ArrayList())
        }
    }

    /**
     * 照片点击事件回调
     */
    fun setOnSelectPhotoListener(listener: ((ArrayList<String>) -> Unit)) {
        onSelectPhotoListener = listener
    }

    fun setOnTakePhotoListener(listener: (() -> Unit)) {
        onTakePhotoListener = listener
    }


    fun setPhotoNumberText(imageCount: Int) {
        val color = ContextCompat.getColor(requireActivity(), R.color.black)
        val foregroundColorSpan = ForegroundColorSpan(color)
        val str = getString(R.string.item_picture_limit, imageCount)
        val start = str.indexOf(":")
        if (start >= 0) {
            val spannableString = SpannableString(str)
            spannableString.setSpan(
                foregroundColorSpan,
                start + 1,
                str.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            mVDB.importInfoText.text = spannableString
        } else {
            mVDB.importInfoText.text = str
        }
    }


    override fun onClick(view: View) {
        when (view.id) {
            R.id.btn_next_photo -> {
                if (limitMax != -1 && limitMin != -1){
                    //选取范围数量
                    if (photoAdapter.itemCount < limitMin) {
                        Toast.makeText(requireActivity(), "至少选择${limitMin}个媒体", Toast.LENGTH_SHORT).show()
                        return
                    }
                    onSelectPhotoListener.invoke(photoAdapter.mData)
                }else{
                    onSelectPhotoListener.invoke(photoAdapter.mData)
                }
            }
        }
    }


}


